/*
 * CourseController.java
 * Copyright 2018 Qunhe Tech, all rights reserved.
 * Qunhe PROPRIETARY/CONFIDENTIAL, any form of usage is subject to approval.
 */

package com.bearox.trans.controller;

import com.bearox.trans.data.domain.SafetyCourse;
import com.bearox.trans.data.dto.SafetyCourseDto;
import com.bearox.trans.data.vo.SafetyCourseVo;
import com.bearox.trans.service.SafetyCourseService;
import com.bearox.trans.utils.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Bearox
 */
@RestController
public class CourseController {
    private final SafetyCourseService safetyCourseService;

    public CourseController(final SafetyCourseService safetyCourseService) {
        this.safetyCourseService = safetyCourseService;
    }

    @PostMapping("/api/course/add")
    public Result addCourse(@RequestBody final SafetyCourseVo safetyCourseVo) {
        final SafetyCourseDto safetyCourseDto = new SafetyCourseDto();
        BeanUtils.copyProperties(safetyCourseVo, safetyCourseDto);
        return Result.ok(safetyCourseService.add(safetyCourseDto));
    }

    @GetMapping("/api/course/list")
    public Result getCourseList(
            @RequestParam(value = "start", defaultValue = "0") final long start,
            @RequestParam(value = "num", defaultValue = "10") final int num) {
        List<SafetyCourseDto> safetyCourseDtos = safetyCourseService.getCourseList(start, num);
        return CollectionUtils.isEmpty(safetyCourseDtos) ? Result.ok() :
                Result.ok(safetyCourseDtos.stream().map(a -> {
                    final SafetyCourseVo safetyCourseVo = new SafetyCourseVo();
                    BeanUtils.copyProperties(a, safetyCourseVo);
                    return safetyCourseVo;
                }).collect(Collectors.toList()));
    }
}
